package net.zubara.esni.core.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import net.zubara.esni.core.CoreMessages;

import org.apache.commons.lang.StringUtils;

public class CoreUtil {

	/**
	 * Generate an MD5 hash of the given {@link String}.
	 * 
	 * @param string
	 *            The string for which an MD5 hash is calculated.
	 * @return The MD5 hash of the given {@link String}.
	 * @throws IllegalStateException
	 *             If MD5 hashing isn't supported on this platform (should never
	 *             occur).
	 */
	public static String generateMd5(String string) {
		try {
			MessageDigest messageDigest = MessageDigest.getInstance(ECoreConstant.MD5.value());
			byte[] bytes = string.getBytes(ECoreConstant.UTF8.value());

			StringBuilder result = new StringBuilder();
			for (byte b : messageDigest.digest(bytes)) {
				result.append(Integer.toHexString((b & 0xf0) >>> 4));
				result.append(Integer.toHexString(b & 0x0f));
			}
			return result.toString();
		} catch (NoSuchAlgorithmException e) {
			// Should never happen
			throw new IllegalStateException(CoreMessages.CoreUtil_MD5NotAvailable, e);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return StringUtils.EMPTY;
	}

}
